<template>
  <div>
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :http-request="upload"
      :before-upload="beforeAvatarUpload"
    >
      <!-- 上传后展示的图片 -->
      <img v-if="imageUrl" :src="imageUrl" class="avatar">
      <!-- 默认的加号图片 -->
      <i v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>

  </div>
</template>

<script>
export default {
  data() {
    return {
      imageUrl: ''
    }
  },
  methods: {
  // 上传之前对文件的限制处理：格式、大小等
  //  :before-upload="beforeAvatarUpload"
    beforeAvatarUpload(file) {
      const fileList = [
        'image/jpeg',
        'image/png'
      ]
      const isType = fileList.includes(file.type)
      const isLt100kb = file.size / 1024 < 100
      if (!isType) {
        this.$message.error('上传头像图片只能是 PNG 格式!')
      }
      if (!isLt100kb) {
        this.$message.error('上传头像图片大小不能超过 5MB!')
      }
      return isType && isLt100kb
    },
    upload(file) {
      console.log(file)
      this.imageUrl = `http://likede2-java.itheima.net/image/${file.file.name}`
    }

  }
}
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
